package com.mqtt.ui.activity;

import android.content.Intent;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.Toast;

import com.mqtt.Configure;
import com.mqtt.MqttApplication;
import com.mqtt.R;
import com.mqtt.dao.UpdateMqttConnection;
import com.mqtt.mqtt.MqttConnectionBean;
import com.mqtt.ui.base.BaseActivity;
import com.mqtt.util.SharePreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.litepal.LitePal;

import java.util.List;

import butterknife.BindView;

/**
 * @Author xiaowen
 * @Email xiaowen.wxf@google.com
 * @Date 2018/10/19 .
 * @Description This is EditConnectionActivity.
 */

public class EditConnectionActivity extends BaseActivity {

    @BindView(R.id.client_id)
    EditText mEtClientId;
    @BindView(R.id.hostname)
    EditText mEtHostname;
    @BindView(R.id.add_connection_port)
    EditText mEtPort;
    @BindView(R.id.clean_session_switch)
    Switch mSwCleanSession;
    @BindView(R.id.username)
    EditText mEtUserName;
    @BindView(R.id.password)
    EditText mEtPassWord;
    @BindView(R.id.tls_server_key)
    EditText mEtTlsServerKey;
    @BindView(R.id.tls_client_key)
    EditText mETTlsClientKey;
    @BindView(R.id.timeout)
    EditText mEtTimeout;
    @BindView(R.id.keepalive)
    EditText mEtKeepAlive;
    @BindView(R.id.lwt_topic)
    EditText mEtTopic;
    @BindView(R.id.lwt_message)
    EditText mEtMessage;
    @BindView(R.id.lwt_qos_spinner)
    Spinner mQosSpinner;
    @BindView(R.id.retain_switch)
    Switch mSwRetain;

    private Integer[] qos = {0, 1, 2};

    private int mQos = 2;

    public static final String EDIT_FLAG = "EDIT_FLAG";

    @Override
    public String getTitleName() {
        return getString(R.string.add_new_service);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_edit_connection;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.edit_connection_nav, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.edit_connection_check) {
            getInputViewData();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void initData() {
        Intent intent = getIntent();
        int qot = 2;
        try {
            if (intent.getBooleanExtra(EDIT_FLAG, false)) {
                MqttApplication application = (MqttApplication) getApplication();
                MqttConnectionBean mqttConnectionBean = application.getmTmpMqttBean();
                qot = mqttConnectionBean.getQos();
                setData(mqttConnectionBean);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        ArrayAdapter<Integer> spinnerAdapter = new ArrayAdapter<Integer>(this, android.R.layout.simple_spinner_item, qos);
        //下拉的样式res
        spinnerAdapter.setDropDownViewResource(R.layout.item_spinner_edit_connection);
        mQosSpinner.setAdapter(spinnerAdapter);
        mQosSpinner.setSelection(qot);
        mQosSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                mQos = i;
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
    }

    private void getInputViewData() {
        String clientId = getText(mEtClientId);
        String hostName = getText(mEtHostname);
        String port = getText(mEtPort);
        String userName = getText(mEtUserName);
        String passWord = getText(mEtPassWord);
//        String serverKey = getText(mEtTlsServerKey);
//        String clientKey = getText(mETTlsClientKey);
        int timeOut = Integer.valueOf(getText(mEtTimeout));
        int keepAlive = Integer.valueOf(getText(mEtKeepAlive));
        String topic = getText(mEtTopic);

        if (TextUtils.isEmpty(clientId)) {
            Toast.makeText(this, "clientId 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(hostName)) {
            Toast.makeText(this, "server 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(port)) {
            Toast.makeText(this, "port 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(userName)) {
            Toast.makeText(this, "userName 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(passWord)) {
            Toast.makeText(this, "passWord 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if (TextUtils.isEmpty(topic)) {
            Toast.makeText(this, "Topic 不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

//        String message = getText(mEtMessage);

        MqttConnectionBean mqttBean = new MqttConnectionBean.Builder()
                .setClientId(clientId)
                .setHost(hostName)
                .setPort(port)
                .setUserName(userName)
                .setPassword(passWord)
                .setConnectionTimeout(timeOut)
                .setKeepAliveInterval(keepAlive)
                .setTopic(topic)
                .setCleanSession(mSwCleanSession.isChecked())
                .setRetained(mSwRetain.isChecked())
                .setQos(mQos)
                .build(this);
        try {
            List<MqttConnectionBean> mqttConnectionBeans = LitePal.where("broker_ip = ?", mqttBean.getBroker_ip()).find(MqttConnectionBean.class);
            for (MqttConnectionBean bean : mqttConnectionBeans) {
                bean.delete();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        mqttBean.save();
        MqttApplication.mMqttConnectionBean = mqttBean;
        SharePreferenceUtil.setString(this, Configure.CURRENT_IP, mqttBean.getBroker_ip());
        EventBus.getDefault().post(new UpdateMqttConnection(mqttBean));
        finish();
    }


    public void setData(MqttConnectionBean data) {
        mEtClientId.setText(data.getClientId());
        mEtHostname.setText(data.getHost());
        mEtPort.setText(data.getPort());
        mSwCleanSession.setChecked(data.isCleanSession());
        mEtUserName.setText(data.getUserName());
        mEtPassWord.setText(data.getPassword());
        mEtTimeout.setText(String.valueOf(data.getConnectionTimeout()));
        mEtKeepAlive.setText(String.valueOf(data.getKeepAliveInterval()));
        mEtTopic.setText(data.getTopic());
        mSwRetain.setChecked(data.isRetained());

    }
}
